import { Mesh, MeshPhongMaterial, Object3D } from "three";
import { URDFJoint } from "urdf-loader";

export function changeHighlightMaterial(joint: URDFJoint | Object3D, revert = false, allJoint = false, material = highlightMaterial)
{
    const traverse = (object3d: Object3D) =>
    {
        if (object3d.type === "Mesh")
        {
            const mesh = object3d as Mesh;
            if (revert)
            {
                if (mesh["__origMaterial"])
                {
                    mesh.material = mesh["__origMaterial"];
                    delete mesh["__origMaterial"];
                }
            }
            else
            {
                mesh["__origMaterial"] = mesh.material;
                mesh.material = material;
            }
        }
        if (joint === object3d || allJoint || !isJoint(object3d))
        {
            for (let i = 0; i < object3d.children.length; i++)
            {
                const child = object3d.children[i];
                if (!child["isURDFCollider"])
                {
                    traverse(object3d.children[i]);
                }
            }
        }
    };

    traverse(joint);
}

function isJoint(j: any): j is URDFJoint
{
    return j.isURDFJoint && j.jointType !== 'fixed';
};

// The highlight material
const highlightMaterial =
    new MeshPhongMaterial({
        shininess: 10,
        color: 0xffffff,
        emissive: 0xffffff,
        emissiveIntensity: 0.25,
    });